package wint.mvc.view.types.json;

import java.io.Writer;
import java.util.Map;

import wint.lang.WintException;
import wint.lang.magic.MagicClass;
import wint.lang.magic.MagicObject;
import wint.mvc.template.Context;

public class DefaultJsonRender implements JsonRender {

	static final Class<?>[] JSON_OBJECT_CONSTRUCTOR_MAP_TYPES = new Class<?>[] { Map.class };
	
	static final Class<?>[] JSON_OBJECT_CONSTRUCTOR_OBJECT_TYPES = new Class<?>[] { Object.class };
	
	static final Class<?>[] JSON_OBJECT_WRITE_TYPES = new Class<?>[] { Writer.class };
	
	static final Class<?>[] JSON_OBJECT_PUT_TYPES = new Class<?>[] { String.class, Object.class };
	

	public void render(Context context, Writer writer) {
		try {
			MagicClass jsonObjectClass = MagicClass.forName("org.json.JSONObject");
			MagicObject jsonObject = jsonObjectClass.newInstance();
			for (Map.Entry<String, Object> entry : context.getAll().entrySet()) {
				String name = entry.getKey();
				Object obj = entry.getValue();
				Object json =  toJSONObject(obj);
				jsonObject.invoke("put", JSON_OBJECT_PUT_TYPES, new Object[] {name, json});
			}
			jsonObject.invoke("write", JSON_OBJECT_WRITE_TYPES, new Object[] { writer });
		} catch (Exception e) {
			throw new WintException(e);
		}
	}
	
	protected MagicObject toJSONObject(Object obj) {
		MagicClass jsonObjectClass = MagicClass.forName("org.json.JSONObject");
		MagicObject jsonObject = jsonObjectClass.newInstance(JSON_OBJECT_CONSTRUCTOR_OBJECT_TYPES, new Object[] { obj });
		return jsonObject;
	}

}
